package br.com.artsy.vraptor;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.transaction.annotation.Transactional;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;

@Intercepts
public class TransactionInterceptor implements Interceptor {
	private final Session session;

	public TransactionInterceptor(Session session) {
		this.session = session;
	}

	public boolean accepts(ResourceMethod method) {
		return method.containsAnnotation(Transactional.class);
	}

	public void intercept(InterceptorStack stack, ResourceMethod method,Object instance) 
	{
		Transaction tx = session.beginTransaction();
		try {
			stack.next(method, instance);
			tx.commit();
		} catch (Exception e) {
			if (tx.isActive()) {
				tx.rollback();
			}
			throw new InterceptionException(e);
		}
	}
}
